<template>
  <div>
    <div class="operate">
      <el-button link type="primary" @click="operateRow('add')" class="btnhover" style="
            width: 90px;
            height: 30px;
            background-color: #ff9900;
            color: rgba(255, 255, 255, 1);
          ">新增组织</el-button>
      <el-form @submit.prevent="getPartyOrganization">
        <el-form-item label="组织名称" style="margin-right: 15px;margin-left: 13px;">
          <el-input v-model="orgName" placeholder="" @keyup.enter="getPartyOrganization" style="width: 200px" />
        </el-form-item>
      </el-form>
      <el-button @click="getPartyOrganization" class="btn btnsearch">查询</el-button>
      <el-button @click="handleReset" class="btn btnreset">重置</el-button>
    </div>
    <div class="mt-0">
      <el-table v-loading="loading" element-loading-text="Loading..." :data="tableData"
        :header-cell-style="headerCellStyle" style="width: 100%" row-key="id" height="calc(100vh - 260px)"
        default-expand-all>
        <el-table-column prop="name" class="ml-20px" label="组织名称" align="left" show-overflow-tooltip min-width="300">
          <template #default="scope">
            <div class="namecont">
              {{ scope.row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="组织类型" show-overflow-tooltip align="center" min-width="200">
          <template #default="{ row }">
            <div class="namecont">
              {{ partyTypeObj[row.category] }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="120">
          <template #default="{ row }">
            <el-button type="primary" link @click="operateRow('edit', row)">编辑</el-button>
            <el-button type="primary" link @click="operateRow('del', row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :title="dialogTitle" v-model="operateVisible" width="50%" destroy-on-close>
      <DynamicForm ref="dynamicForm" :formObj="state.formData" :formItemList="formItemList" :rules="state.rules"
        autoRules />
      <template #footer>
        <span>
          <el-button @click="operateVisible = false">取消</el-button>
          <el-button type="warning" @click="submitPartyOrganization">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ElMessageBox } from 'element-plus'
import partyOrganizationApi from '@/api/spb/organizationManage/partyOrganization'
import DynamicForm from '../../components/DynamicForm.vue'

const dynamicForm = ref()
const message = useMessage()
const operateVisible = ref(false)
const dialogTitle = ref('')
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(true) // 列表加载中
const orgName = ref('')

const state = reactive({
  formData: {},
  rules: {
    name: [{ required: true, message: '组织名称不能为空！', trigger: 'blur' }],
    category: [{ required: true, message: '组织类型不能为空！', trigger: 'change' }]
  }
})
const formItemList = computed(() => {
  return [
    {
      label: '组织名称',
      name: 'name',
      require: true,
      type: 'input'
    },
    {
      label: '组织类型',
      name: 'category',
      require: true,
      type: 'select',
      options: [
        {
          value: 0,
          label: '党委'
        },
        {
          value: 1,
          label: '党总支'
        },
        {
          value: 2,
          label: '党支部'
        },
        {
          value: 3,
          label: '党小组'
        },
        {
          value: 4,
          label: '工会'
        },
        {
          value: 5,
          label: '团委'
        },
        {
          value: 6,
          label: '其他'
        }
      ]
    },
    {
      label: '上级组织',
      name: 'parentId',
      require: false,
      type: 'treeSelect',
      options: tableData.value
    },
    {
      label: '组织职责',
      name: 'responsibility',
      require: false,
      type: 'input'
    }
  ]
})

const headerCellStyle = computed(() => {
  return { background: '#f0f0f0' }
})

const partyTypeObj = {
  0: '党委',
  1: '党总支',
  2: '党支部',
  3: '党小组',
  4: '工会',
  5: '团委',
  6: '其他'
}
//处理树形数据加value和label
function traverse(nodes) {
  nodes.forEach(node => {
    if (node.id) {
      node.label = node.name;
      node.value = node.id;
    }
    if (node.children && Array.isArray(node.children)) {
      traverse(node.children);
    }
  })
}
// 获取党组织管理列表
function getPartyOrganization() {
  const data = {
    pageNo: currentPage.value,
    pageSize: pageSize.value,
    name: orgName.value
  }
  partyOrganizationApi.operatePartyOrganization('list', data, null).then((res) => {
    let cloneData = JSON.parse(JSON.stringify(res))      // 对源数据深度克隆
    cloneData = cloneData.filter(father => {                      // 循环所有项，并添加children属性
      let branchArr = cloneData.filter(child => father.id == child.parentId)  // 返回每一项的子级数组
      branchArr.length > 0 ? father.children = branchArr : ''   //给父级添加一个children属性，并赋值
      return father.parentId == 0     //返回第一层
    })
    traverse(cloneData)
    if (cloneData.length === 0) {
      tableData.value = res
    } else {
      tableData.value = cloneData
    }
    loading.value = false
  }).catch(error => {
    loading.value = false
  })
}

// 新增/编辑党组织
function submitPartyOrganization() {
  dynamicForm.value.validateForm(() => {
    const data = dynamicForm.value.getFormData()
    const type = dialogTitle.value.includes('新增') ? 'create' : 'update'
    partyOrganizationApi.operatePartyOrganization(type, data, null).then(() => {
      getPartyOrganization()
      operateVisible.value = false
      message.success(`${dialogTitle.value}成功`)
    })
  })
}

// 删除党组织
function delPartyOrganization(row) {
  const params = {
    id: row.id
  }
  ElMessageBox.confirm(`确认删除【${row.name}】吗？删除当前党组织会删除当前党组织下所有党员和领导班子，请谨慎操作！`, '提示', {
    confirmButtonText: '确 认',
    cancelButtonText: '取 消',
    type: 'error',
  }).then(() => {
    partyOrganizationApi.operatePartyOrganization('delete', null, params).then(() => {
      getPartyOrganization()
      operateVisible.value = false
      message.success(`删除${row.name}成功`)
    })
  })
}

// 表格操作
function operateRow(type, row) {
  if (type === 'del') {
    delPartyOrganization(row)
    return
  }
  state.formData = type === 'add' ? {} : row
  dialogTitle.value = `${type === 'add' ? '新增' : '编辑'}党组织`
  operateVisible.value = true
}

// 重置操作
function handleReset() {
  currentPage.value = 1
  pageSize.value = 20
  orgName.value = ''
  getPartyOrganization()
}

onMounted(() => {
  getPartyOrganization()
})
</script>

<style lang="scss" scoped>
@import url('../../styles/global.css');

.operate {
  display: flex;
}

::v-deep .el-table .cell {
  display: flex;
  justify-content: center !important;
  align-items: center;
}

::v-deep .el-table .cell:first-child {
  justify-content: left !important;
}

.namecont {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.btn {
  width: 80px;
  height: 30px;
  line-height: 20px;
  border-radius: 5px;
  font-size: 14px;
  text-align: center;
}

.btnreset {
  background-color: rgba(255, 255, 255, 1);
  border: 1px solid rgba(187, 187, 187, 1);
  color: rgba(142, 142, 142, 1);
}

.btnsearch {
  background-color: #cc352f;
  color: rgba(255, 255, 255, 1);
  border: 1px solid #cc352f;
}

.btn:hover {
  opacity: 0.8;
}

.btnhover:hover {
  opacity: 0.8;
}

::v-deep .el-form-item__label {
  font-weight: 500;
}

::v-deep .el-input__wrapper.is-focus {
  box-shadow: 0 0 0 1px #cc352f;
}
</style>
